package com.ease.jdbc.oracle;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FilenameUtils;

import com.ease.common.util.Detect;
import com.ease.common.util.FileUtil;
import com.ease.common.util.StreamUtil;
import com.ease.jdbc.oracle.vo.SqlLoaderParam;

/**
 * // http://blog.csdn.net/xy_liwei/article/details/7493922
 *
 * @author nathanleewei
 *
 */
public class SqlLoaderTemplate extends Detect {

	private String userId;

	public static String filePath(String folder, String fileName) {
		return FilenameUtils.normalize(folder + '/' + fileName);
	}

	public String sqlldr(SqlLoaderParam sqlLoaderParam, SqlLoaderControlCallback sqlLoaderControlCallback) {

		try {

			String control = sqlLoaderControlCallback.control();
			FileUtil.write(sqlLoaderParam.getCtlFileFolder(), sqlLoaderParam.getCtlFileName(), control);

			if (!notEmpty(sqlLoaderParam.getLogFileFolder())) {
				sqlLoaderParam.setLogFileFolder(sqlLoaderParam.getCtlFileFolder());
			}
			if (!notEmpty(sqlLoaderParam.getLogFileName())) {
				sqlLoaderParam.setLogFileName(sqlLoaderParam.getCtlFileName() + ".log");
			}

			String sqlLoaderCommand = "sqlldr userId=" + userId + " control='" + filePath(sqlLoaderParam.getCtlFileFolder(), sqlLoaderParam.getCtlFileName()) + "' data='"
					+ filePath(sqlLoaderParam.getDataFileFolder(), sqlLoaderParam.getDataFileName()) + "' log='" + filePath(sqlLoaderParam.getLogFileFolder(), sqlLoaderParam.getLogFileName())
					+ "' rows=5000 bindsize=10485760 parallel=true";
			System.out.println("sqlLoaderCommand: " + sqlLoaderCommand);
			Process loaderProcess = Runtime.getRuntime().exec(sqlLoaderCommand);

			InputStream inputStream = loaderProcess.getInputStream();
			String returnMessage = StreamUtil.inputStream2String(inputStream, "GB2312");
			loaderProcess.waitFor();
			return returnMessage;
			// log.info("[1.月客户流量CTL脚本执行结束,已导入数据,生成日志文件" + logFile + ",耗时" + stopWatch.getTotalTimeSeconds()+
			// "s!]");

			// 执行存储过程，比对数据进入到正式库中，并且添加流量信息
			// custAgrDAO.addCust("1");
			// long end2 = System.currentTimeMillis();
			// timeLoss = (end2 - end) / 1000;
			// logger.info("[1.周客户流量CTL脚本执行结束,已导入数据,生成日志文件" + logFile + ",耗时" + timeLoss
			// + "s!]");
			// }

		} catch (IOException e) {

			e.printStackTrace();
			// logger.error("导入月客户流量文件，名称为："+fileName+"发生IO异常，异常原因为："+e.getMessage());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @return the userId
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * @param userId
	 *            the userId to set
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

}
